<?php

if (!defined('ABSPATH')) {
    exit();
}
class CMC_Top
{

    public function __construct()
    {
        require_once CMC_PATH . '/includes/cmc-functions.php';
        require_once CMC_PATH . '/includes/cmc-helpers.php';
        add_action('wp_enqueue_scripts', 'cmc_register_scripts');
        add_shortcode('cmc-top', array($this, 'cmc_top_gainer_losers_shortcode'));

        add_action('wp_ajax_get_top_gl', array($this, 'gainer_lossers_callback'));
        add_action('wp_ajax_nopriv_get_top_gl', array($this, 'gainer_lossers_callback'));

    }

    public function cmc_top_gainer_losers_shortcode($atts, $content = null)
    {

        $atts = shortcode_atts(array(
            'id' => '',
            'type' => 'gainers',
            'layout' => 'basic',
            'currency' => 'USD',
            'show-coins' => 10,
        ), $atts);
        $topclass = '';
        $topclass = '';
        $output = '';
        $get_license = get_option('cmc_license_registration');
        $purchased_code = isset($get_license["cmc-purchase-code"]) ? $get_license["cmc-purchase-code"] : '';
        // Do not proceed further if
        $notice = "";
        if (empty($purchased_code)) {
            $notice = __('<b>Please enter and activate your license key for Coin Market Cap plugin for unrestricted and full access of all premium features.</b><br>', 'cmc');
        }
        if (!cmc_check_required_settings()) {
            $api_option = get_option("openexchange-api-settings");

            $api_type = (isset($api_option['select_api'])) ? $api_option['select_api'] : "coingecko";
            if ($api_type == "coingecko") {
                return __('Please enter Coingecko Free Api Key to get this plugin works', 'cmc');

            } else if ($api_type == "coinmarketcap") {
                return __('Please enter CoinMarketcap  Api Key to get this plugin works', 'cmc');

            } else if ($api_type == "both_coingecko" || $api_type == "both_coinmarketcap") {
                return __('Please enter Coingecko & CoinMarketcap Api Key to get this plugin works', 'cmc');

            }

            return __('Please enter Coingecko Free Api Key to get this plugin works', 'cmc');
        }
        wp_enqueue_style('cmc-bootstrap');
        wp_enqueue_style('cmc-custom');
        wp_enqueue_script('cmc-datatables');
        wp_enqueue_script('crypto-numeral');
        wp_enqueue_script('top-gainer-losers', CMC_URL . 'assets/js/top-gainer-losers.js', array('jquery', 'cmc-datatables'), CMC, true);
        wp_localize_script(
            'top-gainer-losers',
            'gl_data_object',
            array(
                'ajax_url' => admin_url('admin-ajax.php'),
                'nonce' => wp_create_nonce('cmc-ajax-nonce'),
            ));
        $api_option = get_option("openexchange-api-settings");
        $api_type = (isset($api_option['select_api'])) ? $api_option['select_api'] : "coingecko";
        $currency = !empty($atts['currency']) ? $atts['currency'] : "USD";
        $type = $atts['type'];
        $load_only = !empty($atts['show-coins']) ? $atts['show-coins'] : 30;
        $layout = $atts['layout'];
        $single_slug = cmc_get_page_slug();
        $single_page_slug = home_url($single_slug, '/');
        $currency_symbol = cmc_old_cur_symbol($currency);
        $default_logo = CMC_URL . 'assets/coins-logos/default-logo.png';
        $processing_text = "";

        $coins_list = get_transient('top-' . $type . $currency);
        if (false == $coins_list) {
            $coins_data = cmc_get_top_coins($type, $load_only);
            $coinIds = array(); // Initialize an empty array to store the coin_ids
            if ($coins_data) {
                foreach ($coins_data as $item) {
                    if (isset($item->coin_id)) {
                        $coinIds[] = ($api_type == "coinmarketcap" || $api_type == "both_coinmarketcap") ? cmc_coin_array_ids($item->coin_id, true) : $item->coin_id;
                    }
                }
                CMC_api_data::cmc_get_selected_api_ua_data($coinIds, false, true);
            }
        }

        $output .= '<div id="top-gl-wrapper">
		<table data-default-logo="' . esc_attr($default_logo) . '" data-type="' . esc_attr($type) . '" data-load-coins="' . esc_attr($load_only) . '"
		 data-layout="' . esc_attr($layout) . '"
		 data-processing-text="' . esc_attr($processing_text) . '"
		data-currency="' . esc_attr($currency) . '" data-classes="' . esc_attr($type) . '"
		data-fiat-currency-symbol="' . esc_attr($currency_symbol) . '"
		id="cmc-top-' . esc_attr($type) . '" class="table cmc-gainer-lossers cmc-top-' . esc_attr($type) . '  cmc-datatable table-striped table-bordered cmc-table-loader" width="100%">
		<thead><tr>';

        $output .= '<th data-index="name" class="all gl-coin-name" data-single-url="' . esc_attr($single_page_slug) . '" >' . __('Name', 'cmc') . '</th>';
        $output .= '<th data-index="price" class="all gl-coin-price">' . __('Price', 'cmc') . '</th>';
        $output .= '<th data-index="percent_change_24h" class="all  cmc-changes gl-changes">' . __('Changes ', 'cmc') . '<span class="badge  badge-default">' . __('24H', 'cmc') . '</span></th>';
        $output .= '</tr></thead><tbody>';
        $output .= '</tbody></table></div>';

        return $notice . $output;

    }

// gainer losser callback handler
    public function gainer_lossers_callback()
    {
        $nonce = isset($_POST['_wpnonce']) ? sanitize_text_field($_POST['_wpnonce']) : (isset($_SERVER['HTTP_X_WP_NONCE']) ? sanitize_text_field($_SERVER['HTTP_X_WP_NONCE']) : '');
        if (!wp_verify_nonce($nonce, 'cmc-ajax-nonce')) {
            $response = array("dra-" => 1,
                "recordsTotal" => 1,
                "recordsFiltered" => 1, "data" => [], 'error' => 'nonce_failed');

            echo json_encode($response);
            die();
        }

        $single_page_slug = cmc_get_page_slug();
        $i = 0;
        $currency = isset($_POST['currency']) ? esc_sql($_POST['currency']) : "USD";
        $loadCoins = isset($_POST['loadCoins']) ? esc_sql($_POST['loadCoins']) : 30;
        $type = isset($_POST['type']) ? esc_sql($_POST['type']) : '';
        if ($loadCoins != get_transient('top-' . $type . $currency)) {
            delete_transient('top-' . $type . $currency);
        }
        $coins_list = get_transient('top-' . $type . $currency);
        if (false === $coins_list) {
            $coins_list = [];
            $fiat_currency = isset($currency) ? $currency : "USD";
            $bitcoin_price = get_transient('cmc_btc_price');
            $currency_symbol = cmc_old_cur_symbol($fiat_currency);
            $fiat_currency_rate = CMC_api_data::cmc_usd_conversions($fiat_currency);
            $coins_data = cmc_get_top_coins($type, $loadCoins);
            if (is_array($coins_data) && count($coins_data) > 0) {
                foreach ($coins_data as $coin) {
                    $coin = (array) $coin;
                    $coin_id = sanitize_text_field($coin['coin_id']);
                    $coin_symbol = sanitize_text_field(strtoupper($coin['symbol']));
                    $symbol = $coin_symbol;
                    $coin_name = sanitize_text_field(strtoupper($coin['name']));
                    $coin_price = floatval($coin['price']);
                    $usd_market_cap = floatval($coin['market_cap']);
                    $usd_volume = floatval($coin['total_volume']);
                    $coin_html = '';
                    if ($fiat_currency == "USD") {
                        $coin_price = floatval($coin['price']);
                        $market_cap = floatval($coin['market_cap']);
                        $volume = floatval($coin['total_volume']);
                    } else if ($fiat_currency == "BTC") {
                        $coin_price = floatval($coin['price']) / $bitcoin_price;
                        $market_cap = floatval($coin['market_cap']) / $bitcoin_price;
                        $volume = floatval($coin['total_volume']) / $bitcoin_price;
                    } else {
                        $coin_price = floatval($coin['price']) * $fiat_currency_rate;
                        $market_cap = floatval($coin['market_cap']) * $fiat_currency_rate;
                        $volume = floatval($coin['total_volume']) * $fiat_currency_rate;
                    }
                    $local_logo = coin_list_logo($coin['coin_id'], $size = 32);
                    $percent_change_24h = number_format(floatval($coin['percent_change_24h']), '2', '.', '');
                    $coins_list[$i]['name'] = $coin_name;
                    $coins_list[$i]['price'] = $coin_price;
                    $coins_list[$i]['market_cap'] = $market_cap;
                    $coins_list[$i]['percent_change_24h'] = $percent_change_24h;
                    $coins_list[$i]['symbol'] = $symbol;
                    $coins_list[$i]['logo'] = esc_url(($local_logo === false) ? CMC_COINS_LOGO . sanitize_text_field($coin['logo']) : $local_logo);
                    $coins_list[$i]['coin_id'] = $coin_id;
                    $i++;
                }
                set_transient('top-' . $type . $fiat_currency, $coins_list, 60 * MINUTE_IN_SECONDS);
            }
        } else {
            $coins_list = (array) $coins_list; // Ensure $coins_list is an array
        }
        $response = array(
            "dra-" => 1,
            "recordsTotal" => 10,
            "recordsFiltered" => 10,
            "data" => $coins_list ? $coins_list : array(),
        );
        echo json_encode($response);
        exit();
    }

}
